// depends on OQueue
objx("objx.OWorkQueue").requires("objx.OInterval", "objx.OQueue");

var OWorkQueue = OClass(OQueue, {
	
	interval: null,
	working: false,
	
	onWorking: OEvent,
	onIdle: OEvent,
	
	init: function(key, interval) {
		
		// call the base init method
		this.base_init.apply(this, arguments);
		
		// save the key
		key = this.key = key || Date();
		interval = this.interval = interval || 1000;

		// create the interval to manage this work queue
		OInterval(key, OBind(this.work, this), interval, OIntervalIdle);
		
	},
	
	start: function() {
		
		if (!this.working && this.length > 0) {
			
			// raise the working event
			this.onWorking();
			
			// start work
			this.work();
			
		}
		
	},
	
	work: function() {
		
		if (ODebug) {
			
			var o = this.pop();
			
			if (o.execute) {
				o.execute();
			} else {
				OError("OWorkQueue", "Items pushed to OWorkQueue must have an 'execute' function in order for the queue to execute them.");
			}
			
		} else {
		
			// execute this one
			this.pop().execute();
		
		}
		
		if (this.length > 0) {
		
			// schedule the next one
			OInterval(this.key);
		
		} else {
			
			// finished working
			this.working = false;

			// raise the idle event
			this.onIdle();
			
		}
 		
	}
	
});

OProvides("objx.OWorkQueue");